<?php

namespace App\Http\Controllers\Admin;

use App\Exports\DemandExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\Demand;
use App\Models\Areas;
use App\Models\BidLists;
use App\Models\Buys;
use App\Models\Categorys;
use App\Models\CompanyInfos;
use App\Models\Configs;
use App\Models\Demands;
use App\Models\Mails;
use App\Models\Messages;
use App\Models\QuickDemands;
use App\Models\Stores;
use App\Models\Users;
use App\Models\Wechat;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use Maatwebsite\Excel\Facades\Excel;

class DemandController extends Controller {

    /**
     * 页面
     * @return view
     */
    public function index(Request $request){
        $params = [
            'page' => 1,
            'kwd' => '',
            'status' => 0,
            'cid' => 0,
            'start' => '',
            'end' => '',
        ];
        //如果从代办点击过来，则显示待审核
        $from = $request->get('from',0);
        if ($from == 1){
            $params['status'] = 2;
            $from = 0;
        }
        $params = json_encode($params);
        //获取分类
        $categorys = Categorys::getCascaderList();
        $categorys = json_encode($categorys);
        return view('admin.demand.index',compact('categorys','params'));
    }

    /**
     * 列表数据
     * @param Request $request
     * @return bool
     */
    public function list(Request $request){
        try{
            $params = [
                'kwd' => (string)$request->get('kwd',''),
                'status' => (int)$request->get('status',0),
                'bid' => (int)$request->get('bid',0),
                'cid' => (int)$request->get('cid',0),
                'start' => (string)$request->get('start',''),
                'end' => (string)$request->get('end',''),
                'sort' => (string)$request->get('sort',''),
            ];
            $lists = Demands::getList($params);
            foreach ($lists as $k=>$v){
                $lists[$k]['bid_id'] = BidLists::where('demand_id',$v['id'])->get(['store_id','store_name','bid_time']);//已选择的供应商信息
                $lists[$k]['price'] = floatval($v['price']);
                $lists[$k]['bid_costs'] = floatval($v['bid_costs']);
                $lists[$k]['area'] = Areas::where('id',$v['area'])->value('name');
                if ($v['is_can'] == 2){
                    $lists[$k]['bid_text'] = '<span class="el-tag el-tag--warning">已完成</span>';
                }
            }
//            dd($lists->toArray());
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 编辑
     * @param Request $request
     * @return bool|view
     */
    public function edit(Request $request){
        try{
            $id = (int)$request->get('id',0);
            $quick_id = (int)$request->get('quick_id',0);
            $quick_info = [];
            $quick_mobile = [];
            $quick_userid = [];
            if ($quick_id){
                $quick_info = QuickDemands::findOrFail($quick_id);
                $info['service_cate'] = [1];
                $quick_mobile = QuickDemands::where('id',$quick_id)->value('mobile');
                $quick_userid = QuickDemands::where('id',$quick_id)->value('user_id');
            }
            $quick_info = json_encode($quick_info);
            $quick_id = json_encode($quick_id);
            $quick_mobile = json_encode($quick_mobile);
            $quick_userid = json_encode($quick_userid);

            $info = [];
            $info['reason'] = '';
            if($id){
                $info = Demands::findOrFail($id);
                $info['cate_id'] = [$info['cate_pid'],$info['cate_id']];
                $info['area'] = [$info['area']];
                $info['company_type'] = [$info['company_type']];
                $info['company_industry'] = [$info['company_industry']];
                $info['company_size'] = [$info['company_size']];
                //判断需求是否在截止时间内
                if ($info['end_at'] > date('Y-m-d H:i:s')){
                    $info['end_state'] = 0;//截止前不可修改
                }else{
                    $info['end_state'] = 1;//截止后可修改
                }
                $info['service_cate'] = [$info['service_cate']];
            }
            $info = json_encode($info);

            //获取分类
            $category = Categorys::getCascaderList();
            $categorys = json_encode($category);
            //获取区域
            $area = Areas::getCascaderList();
            $areas = json_encode($area);
            //公司类型
            $company_type = CompanyInfos::getCascaderList(['type'=>1]);
            $company_types = json_encode($company_type);
            //公司行业
            $company_industry = CompanyInfos::getCascaderList(['type'=>2]);
            $company_industrys = json_encode($company_industry);
            //公司类型
            $company_size = CompanyInfos::getCascaderList(['type'=>3]);
            $company_sizes = json_encode($company_size);

            return view('admin.demand.demand_update',compact('info','id','categorys','areas','company_types','company_industrys','company_sizes','quick_id','quick_info','quick_mobile','quick_userid'));
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 更新
     * @param Demand $request
     * @return bool
     */
    public function update(Demand $request)
    {
        try{
            $data = $request->all();
            //如果是快速发布需求，则对应相应的发不者，否则为admin
            if (!empty($data['quick_userid'])){
                $user_id = Users::where('id',$data['quick_userid'])->value('id');
                $username = Users::where('id',$data['quick_userid'])->value('username');
            }else{
                if(!$data['id']){
                    $user_id = 0;
                    $username = 'admin';
                }
            }
            if (!empty($data['link_phone'])){
                if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $data['link_phone'])){
                    return $this->writeJson(1,null,'请填写正确的手机号码');
                }
            }
            //设置投标服务费比例
            $base = Configs::getConfig('base');
            $data['service_cate'] = $data['service_cate'][0];
            if ($data['service_cate'] == 1){
                $data['service_charge'] = $base['call_money'];
            }elseif ($data['service_cate'] == 2){
                $data['service_charge'] = $base['bid_money'];
            }
            //处理分类
            $data['cate_pid'] = $data['cate_id'][0];
            $cate_id = 0;
            if (isset($data['cate_id'][1])){
                $cate_id = $data['cate_id'][1];
            }
            $data['cate_id'] = $cate_id;
            if(!empty($data['quick_userid']) || !$data['id']){
                $data['user_id'] = $user_id;
                $data['user_name'] = $username;
            }

            $data['area'] = empty($data['area']) ? 0 : $data['area'][0];
            $data['company_type'] = empty($data['company_type']) ? 0 : $data['company_type'][0];
            $data['company_industry'] = empty($data['company_industry']) ? 0 : $data['company_industry'][0];
            $data['company_size'] = empty($data['company_size']) ? 0 : $data['company_size'][0];
            if($data['id']){
                $info = Demands::findOrFail($data['id']);
                //如果投保人数未满并且截止时间大于当前时间，可以投标
                if ($data['number'] != $data['limit_num'] && trim(@date('Y-m-d', strtotime($data['end_at']))) > date('Y-m-d')){
                    $data['is_can'] = 1;
                }

                //19-9-20 by z 除正常状态意外其余需给用户发送站内信告知原因 start
                if($data['status'] != 1){
                    $reason = $data['reason'];
                    if(empty($reason)){
                        return $this->writeJson(1, null, '请填写相关状态原因！');
                    }
                    if($data['status'] == 2 || $data['status'] == 3){
                        $title = '需求审核通知';
                    }elseif ($data['status'] == 4){
                        $title = '需求下架通知';
                    }
                    Mails::sendMails($title,$data['reason'],$info['user_id'],1);
                }else{
                    if($info['status'] != 1){
                        Mails::sendMails('需求审核通知','您发布的"' . $info['title'] .'"需求审核通过!请到 个人中心-需求管理中心 查看详情',$info['user_id'],1);
                    }
                }
                //end

                $info->update($data);
                return $this->writeJson(0,null,'修改信息成功');
            }else{
                unset($data['id']);//查询需求标题是否重复
                Demands::create($data);
                if ($data['quick_id'] != 0){
                    QuickDemands::where('id',$data['quick_id'])->update(['type'=>2]);
                }
                return $this->writeJson(0,null,'新增信息成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 拒绝
     * @param Request $request
     * @return bool
     */
    public function lock(Request $request){
        try{
            $id = (int)$request->get('id',0);
            $reason = (string)$request->get('reason', '');
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $info = Demands::findOrFail($id);
            $info->update(['status' => Demands::STATUS_3]);

            //19-9-23 by z 下架发送站内信 start
            Mails::sendMails('需求审核通知',$reason,$info['user_id'],1);
            //end

            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 通过
     * @param Request $request
     * @return bool
     */
    public function active(Request $request){
        try{
            $id = (int)$request->get('id',0);
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $info = Demands::findOrFail($id);
            $info->update(['status' => Demands::STATUS_1]);
            //发送站内信
            if($info['user_id'] != 0){
                $template = [
                    'title' => '需求审核通知',
                    'content' => '您发布的"' . $info['title'] .'"需求审核通过!请到 个人中心-需求管理中心 查看详情',
                    'user_id' => $info['user_id'],
                    'status' => 1,
                    'type' => 1,
                ];
                Mails::create($template);
            }
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 下架
     */
    public function close(Request $request)
    {
        try {
            $id = (int)$request->get('id', 0);
            $reason = (string)$request->get('reason', '');
            if (empty($id)) {
                return $this->writeJson(1, null, '参数错误');
            }
            $info = Demands::findOrFail($id);

            $info->update(['status' => Demands::STATUS_4]);

            //19-9-23 by z 下架发送站内信 start
            Mails::sendMails('需求下架通知',$reason,$info['user_id'],1);
            //end

            return $this->writeJson(0);
        } catch (\Exception $e) {
            return $this->writeJson(1, null, $e->getMessage());
        }
    }

    /**
     * 单个/多个删除
     * @param Request $request
     * @return bool
     */
    public function destroy(Request $request){
        try{
            $id = $request->get('id');
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            if(!is_array($id)){
                $id=[$id];
            }
            //修改软删除 19-7-31
            $data['status'] = -1;
            Demands::whereIn('id',$id)->update($data);
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 投标供应商列表数据
     * @param Request $request
     * @return bool
     */
    public function user_list(Request $request)
    {
        try {
            $user_ids = Stores::where('status',1)->get(['user_id']);
            foreach ($user_ids as $key => $val){
                $ids[] = Users::where('id',$val['user_id'])->value('id');
            }
            $params = [
                'kwd' => (string)$request->get('kwd', ''),
                'type' => (int)$request->get('type', 2),
                'status' => (int)$request->get('status', 1),
                'id' =>  (array)$request->get('ids', 0),
                'ids' =>  $ids,
            ];
            $lists = Users::getList($params);
            return $this->writeJson(0, $lists);
        } catch (\Exception $e) {
            return $this->writeJson(1, null, $e->getMessage());
        }
    }

    /**
     * 指定投标供应商
     * @param Demand $request
     * @return bool
     */
    public function store_update(Request $request)
    {
        try{
            $data = $request->all();
            $info = Demands::findOrFail($data['id']);
            if ($info['number'] == $info['limit_num']){
                return $this->writeJson(1,null,'此需求投标人数已满,请重新选择!');
            }elseif (trim(@date('Y-m-d', strtotime($info['end_at']))) < date('Y-m-d')){
                return $this->writeJson(1,null,'此需求已过截止日期,请重新选择!');
            }
            $data['bid'] = 2;
            $now = date('Y-m-d H:i:s');
            if($data['way'] == 1){
                $cate_id = $info['cate_id'];
                $store_user_id = Stores::whereRaw("FIND_IN_SET($cate_id,cate_id)")->where('status',1)->pluck('user_id');//当前需求二级分类下的店铺
                $gys = Users::whereIn('id',$store_user_id)->where(['type'=>2,'status'=>1])
                    ->where('openid','<>','')->get(['id','mobile','username','openid']);
                foreach ($gys as $key=>$val){
                    if (!empty($val['openid'])){
                        $template_id = 'q4dFPemDuWKWbjy4qxkscL5YNweUtkhrfaeWzgcYlWk';
                        $url = 'http://wap.hrqidian.com/#/hall';
                        $data_arr = [
                            'first' => 'HR新发布了一个业务需求在大厅',
                            'keyword1' => $info['title'],
                            'keyword2' => Categorys::where('id',$info['cate_pid'])->value('name').'-'.Categorys::where('id',$info['cate_id'])->value('name'),
                            'keyword3' => Areas::where('id',$info['area'])->value('name'),
                            'keyword4' => $info['end_at'],
                            'remark' => '立即点击查看业务内容明细或在需求大厅查看更多业务。 HR小启客服',
                        ];
                        $ret = Wechat::wechatSend($val['openid'], $template_id, $url, $data_arr);
                        if ($ret['errcode'] != 0 || $ret['errmsg'] != 'ok'){
                            return $this->writeJson(1,null,'消息推送失败');
                        }
                    }
                }
            }elseif ($data['way'] == 2){
                //移除已投标供应商
                $bids = BidLists::where(['demand_id'=>$data['id']])->get(['store_id']);
                foreach ($bids as $key=>$val){
                    foreach ($data['bid_id'] as $k=>$v){
                        if ($val['store_id'] == (int)$v){
                            unset($data['bid_id'][$k]);
                        }
                    }
                }
                $bid_ids = array_values($data['bid_id']);//重置数组

                $insert = [];
                $mails = [];
                foreach ($bid_ids as $k=>$v){
                    $store_name = Users::where('id',$v)->value('username');
                    $map = [
                        'bid_sn' => Buys::makePaySn($v),
                        'demand_id' => $data['id'],
                        'user_id' => $info['user_id'],
                        'user_name' => $info['user_name'],
                        'store_id' => $v,
                        'store_name' => $store_name,
                        'bid_time' => $now,
                        'bid_fee' => $info['service_charge'] ? $info['service_charge'] : 0,
                        'order_from' => 2,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ];
                    array_push($insert, $map);

                    //发送站内信-需求订单匹配通知
                    $template = [
                        'title' => '需求订单匹配通知',
                        'content' => '我们已于您提前联系达成接收意向,并扣除您'.$info['bid_costs'].'的投标费用，请及时前往"竞标管理中心"获取雇主联系方式，与雇主联系后进行下一步合作；',
                        'user_id' => $v,
                        'status' => 1,
                        'type' => 1,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ];
                    array_push($mails, $template);
                }
                BidLists::insert($insert);
                Demands::where('id',$data['id'])->increment('number', sizeof($bid_ids));//增加投标数量
                Mails::insert($mails);
            }elseif ($data['way'] == 3){
                $store_name = Users::where('id',$data['bid_id'])->value('username');
                $bid = BidLists::where(['store_id'=>$data['bid_id'],'demand_id'=>$data['id']])->value('store_id');
                if(!empty($bid)){
                    return $this->writeJson(1,null,$store_name . '供应商已经投标该需求,请重新选择');
                }
                $map = [
                    'bid_sn' => Buys::makePaySn($data['bid_id']),
                    'demand_id' => $data['id'],
                    'user_id' => $info['user_id'],
                    'user_name' => $info['user_name'],
                    'store_id' => $data['bid_id'],
                    'store_name' => $store_name,
                    'bid_time' => $now,
                    'bid_fee' => $info['service_charge'] ? $info['service_charge'] : 0,
                    'bid_status' => 2,
                    'finnshed_time' => $now,
                    'order_from' => 2,
                ];
                $result = BidLists::create($map);
                //修改其他投标供应商为：未中标
                $list = BidLists::where('demand_id',$data['id'])->where('id','<>',$result['id'])->get(['id']);
                if(empty($list)){
                    foreach ($list as $val){
                        $update = [
                            'bid_status' => 1,
                            'finnshed_time' => date('Y-m-d H:i:s'),
                        ];
                        BidLists::where('id',$val['id'])->Update($update);
                    }
                }
                Demands::where('id',$data['id'])->increment('number',1);//增加投标数量
                Stores::where('user_id',$data['bid_id'])->increment('service',1);//增加成交量

                //发送站内信-需求订单中标通知
                $mails = [
                    'title' => '需求订单匹配通知',
                    'content' => '经平台回访核实，您于' . $map['bid_time'] . '与需求"' . $info['title'] .'达成合作并签订了合同，请及时前往"竞标管理中心"上传合同，谢谢合作。',
                    'user_id' => $data['bid_id'],
                    'status' => 1,
                    'type' => 1,
                ];
                Mails::create($mails);
                //发送系统消息
                $message = [
                    'title' => '恭喜' . $store_name . '成功中标' . $info['title'],
                    'content' => '恭喜' . $store_name . '成功中标' . $info['title'],
                    'type' =>5,
                ];
                Messages::create($message);

                $data['bid'] = 3;
            }
            //改变需求状态
            unset($data['id']); unset($bid_ids); unset($data['bid_count']);
            $info->update($data);
            return $this->writeJson(0,null,'分配成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     *  Excel导出
     * @param Request $request
     * @return bool
     */
    public function exports(Request $request)
    {
        $ids = $request->get('ids');
        $export = new DemandExport($ids);
        //这里可以传参到服务层
        return Excel::download($export, '需求表'.date("Y-m-d H:i:s").'.xlsx');
    }


}
